package com.caocaog.market.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.caocaog.market.annotation.IgnoreAuth;
import com.caocaog.market.entity.*;
import com.caocaog.market.finance.entity.MkBillBase;
import com.caocaog.market.finance.service.MkBillBaseService;
import com.caocaog.market.pay.UnionPaySDX;
import com.caocaog.market.service.*;
import com.caocaog.market.vo.DistanceVo;
import com.caocaog.market.vo.OrderForOneVo;
import com.caocaog.market.vo.ShopInfoVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.util.oConvertUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.Date;

/**
 * 商品订单api-送大侠
 * 暂时和曹操来了逻辑一致 生成订单号/退款单号区别标识
 * 购物车逻辑一致
 * 支付逻辑一致......
 * 如果修改逻辑 请检查是否会影响曹操来了的功能 知悉~
 *
 * @author yuki Guo
 * @date 2022年2月10日15:03:08
 */
@Slf4j
@RestController
@RequiredArgsConstructor
@Api(value = "orderApi", tags = "API-sdx商品订单")
@RequestMapping("/api/order/sdx")
public class ApiSDXOrderController extends BaseController {

    @Autowired
    private IOrderBaseSDXService iOrderBaseSDXService;
    @Autowired
    private MkBillBaseService mkBillBaseService;
    @Autowired
    private UnionPaySDX unionPaySDX;
    @Autowired
    private IOrderPayService orderPayService;
    @Autowired
    private IOrderRefundService orderRefundService;
    @Autowired
    private ShopCartService shopCartService;
    @Autowired
    private ShopPromoService shopPromoService;

    @IgnoreAuth
    @AutoLog(value = "送大侠-首页-周边好物")
    @ApiOperation(value = "送大侠-首页-周边好物(100公里内)", notes = "/{lat}/{lng}\n ")
    @GetMapping(value = "/goodThingsAroundForSDX")
    public Result<?> goodThingsAroundForSDX(@RequestParam("lat") String lat,
                                            @RequestParam("lng") String lng,
                                            @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                            @RequestParam(name = "pageSize", defaultValue = "20") Integer pageSize) {
        return iOrderBaseSDXService.goodThingsAroundForSDX(lat, lng, pageNo, pageSize);
    }

    @IgnoreAuth
    @AutoLog(value = "店铺详情")
    @ApiOperation(value = "店铺详情", notes = "id:门店的id ")
    @PostMapping(value = "/getShopInfo")
    public Result<?> getShopInfo(@RequestBody ShopInfoVo shopInfoVo) {

        return iOrderBaseSDXService.getShopInfo(shopInfoVo);
    }

    @IgnoreAuth
    @AutoLog(value = "店铺内商品列表")
    @ApiOperation(value = "店铺内商品列表", notes = "id:门店的id,分类id ")
    @GetMapping(value = "/getShopOfGoodsList")
    public Result<?> getShopOfGoodsList(GoodsBasic goodsBasic,
                                        @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                        @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {

        return Result.OK(iOrderBaseSDXService.getShopOfGoodsList(goodsBasic, pageNo, pageSize));
    }

    @AutoLog(value = "单商品下订单")
    @ApiOperation(value = "单商品下订单", notes = "单商品下订单")
    @PostMapping(value = "/OrderForOne")
    public Result<?> OrderForOne(@RequestBody OrderForOneVo vo) {

        Member member = verifyUserForApp();
        if (!member.getId().equals(vo.getMemberId())) {
            return Result.error("暂无权限操作~");
        } else if (oConvertUtils.isEmpty(vo.getPayMoney()) ||
                oConvertUtils.isEmpty(vo.getShopId())) {
            return Result.error("参数错误");
        } else {
            return iOrderBaseSDXService.add(vo, member);
        }
    }


    @IgnoreAuth
    @ApiOperation(value = "计算符合的优惠信息", notes = "计算符合的优惠信息")
    @PostMapping(value = "/computeConformPromo")
    public Result<?> computeConformPromo(@RequestBody OrderForOneVo orderForOneVo) {
        return Result.OK(this.iOrderBaseSDXService.computeConformPromo(orderForOneVo));
    }

    @IgnoreAuth
    @ApiOperation(value = "获取店铺优惠信息", notes = "获取店铺优惠信息")
    @GetMapping(value = "/getByShopId")
    public Result<?> getShopPromoByShopId(@ApiParam("shopId") @RequestParam("shopId") String shopId) {
        return Result.OK(this.shopPromoService.getShopPromoByShopId(shopId));
    }

    @AutoLog(value = "订单列表")
    @ApiOperation(value = "订单列表", notes = "params: memberId必传 \n type:类型1：外卖 2：自提 status:-3:退款成功" +
            "\n type和status都不传时,默认查询该用户的所有订单 ", response = OrderBase.class)
    @GetMapping(value = "/selectOrderListForMember")
    public Result<?> selectOrderListForMember(OrderBase orderBase,
                                              @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                              @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        Member member = verifyUserForApp();
        if (!member.getId().equals(orderBase.getMemberId())) {
            return Result.error("暂无权限操作~");
        }
        //全部 配送单 自提单 退款
        IPage<OrderBase> orderBaseList = iOrderBaseSDXService.selectOrderListForMember(orderBase, pageNo, pageSize);
        log.info("订单列表" + orderBaseList.getRecords().size());
        return Result.OK(orderBaseList);
    }

    @IgnoreAuth
    @AutoLog(value = "获取订单其他信息")
    @ApiOperation(value = "获取订单其他信息", notes = "获取订单其他信息")
    @GetMapping(value = "/selectOrderInfo")
    public Result<?> selectOrderInfo(@RequestParam("id") String id) {

        return Result.OK(iOrderBaseSDXService.selectOrderInfo(id));
    }

    @AutoLog(value = "微信小程序订单支付")
    @ApiOperation(value = "微信小程序订单支付")
    @GetMapping(value = "/orderPay")
    public Result<?> orderPay(@ApiParam("orderId") @RequestParam("orderId") String orderId,
                              @ApiParam("支付金额") @RequestParam("payMoney") String payMoney) {
        Member member = verifyUserForApp();
        OrderBase orderBase = iOrderBaseSDXService.getById(orderId);
        if (null == orderBase) {
            return Result.error("参数错误,订单不存在~");
        }
        if (!orderBase.getStatus().equals("0")) {
            String errorMsg = "参数错误,订单不是待支付状态:" + orderBase.getOrderNo() + "-" + orderBase.getStatus();
            log.error(errorMsg);
            return Result.error(errorMsg);
        }
        OrderPay orderPay = orderPayService.getOne(new QueryWrapper<OrderPay>().eq("order_id", orderId));
        if (null == orderPay) {
            return Result.error("参数错误,订单异常~");
        }
        if (new BigDecimal(orderPay.getPayAmount()).compareTo(new BigDecimal("0.01")) < 0) {
            log.error("payAmount:" + orderPay.getPayAmount());
            return Result.error("参数错误,支付金额异常~");
        }
        if (new BigDecimal(orderPay.getPayAmount()).compareTo(new BigDecimal(payMoney))!=0) {
            return Result.error("参数错误~");
        }
        orderPay.setPayTime(new Date());
        orderPayService.updateById(orderPay);
        String openid = null==member.getWxUnionid()?member.getWxOpenid():member.getWxUnionid();
        return Result.OK(unionPaySDX.pay(orderId, "", "送大侠-订单支付", null, openid));
    }

    // 取消订单
    @AutoLog(value = "取消订单")
    @ApiOperation(value = "取消订单-待付款的可取消")
    @GetMapping(value = "/cancelOrder")
    public Result<?> cancelOrder(@ApiParam("orderId") @RequestParam("orderId") String orderId) {
        Member member = verifyUserForApp();
        OrderBase orderBase = iOrderBaseSDXService.getById(orderId);
        if (null == orderBase) {
            return Result.error("参数错误,订单不存在~");
        }
        if (!orderBase.getStatus().equals("0")) {
            String errorMsg = "参数错误,订单不是待付款状态:" + orderBase.getOrderNo() + "-" + orderBase.getStatus();
            log.error(errorMsg);
            return Result.error(errorMsg);
        }
        return iOrderBaseSDXService.cancelOrder(orderId, member);

    }


    @AutoLog(value = "退款")
    @ApiOperation(value = "退款订单")
    @PostMapping(value = "/refundOrder")
    public Result<?> refundOrder(@RequestBody OrderRefund orderRefund) {
        log.info("退款订单====>" + orderRefund.toString());
        Member member = verifyUserForApp();
        if (!member.getWxOpenid().equals(orderRefund.getOpenid())) {
            return Result.error("参数错误~");
        }
        OrderBase orderBase = iOrderBaseSDXService.getOne(new QueryWrapper<OrderBase>().eq("order_no", orderRefund.getOrderNo()).last(" limit 1 "));
        if (null == orderBase) {
            return Result.error("参数错误,订单不存在~");
        }
        if (Integer.parseInt(orderBase.getStatus()) == -2) {
            OrderRefund orderRefund1 = orderRefundService.getOne(new QueryWrapper<OrderRefund>()
                    .eq("order_id", orderRefund.getOrderId()));
            String errorMsg = "";
            if (null != orderRefund1) {
                if (orderRefund1.getAudit() == 1) {
                    errorMsg = "您的订单退款已审核通过，请后续注意退款到账";
                } else {
                    errorMsg = "您的订单退款正在审核中,如有问题请联系商家";
                }

                log.error(errorMsg);
                return Result.error(errorMsg);
            }
        }
        if (orderBase.getStatus().equals("-3")) {
            return Result.error("退款已完成");
        }
        if (Integer.parseInt(orderBase.getStatus()) < 1) {
            String errorMsg = "参数错误,订单无法申请退款:" + orderBase.getOrderNo() + "-" + orderBase.getStatus();
            log.error(errorMsg);
            return Result.error(errorMsg);
        }
        //判断 结算状态 bill  mkBillBaseService
        MkBillBase mkBillBase = mkBillBaseService.findBillIsExist(orderBase.getOrderNo());
        if (oConvertUtils.isNotEmpty(mkBillBase) && mkBillBase.getPayStatus() != 1) {
            return Result.error("不能申请退款了哟，如有问题，请联系店家～");
        }

        return iOrderBaseSDXService.refundOrder(orderRefund, member);
    }

    // 获取配送费  计算两个经纬度(用户地址和店铺)之间的距离
    @AutoLog(value = "获取配送费")
    @ApiOperation(value = "获取配送费 获取默认常用地址", notes = "params:1. gpsTo和shopId amount必传  \n 2.memberId和 gpsfrom 都不传时,返回用户的一个常用地址,距离和配送费")
    @PostMapping(value = "/getDeliveryAmount")
    public Result<?> getDeliveryAmount(@RequestBody DistanceVo vo) {

        Member member = verifyUserForApp();
        if (oConvertUtils.isEmpty(vo.getGpsToLat())
                || oConvertUtils.isEmpty(vo.getGpsFromLng())
                || oConvertUtils.isEmpty(vo.getShopId())
                || oConvertUtils.isEmpty(vo.getAmount())) {
            return Result.error("参数错误");
        }
        if (oConvertUtils.isEmpty(vo.getMemberId())) {
            vo.setMemberId(member.getId());
        }

        DistanceVo distanceVo = iOrderBaseSDXService.getDeliveryAmount(vo);

        return Result.OK(distanceVo);
    }

    /**
     * 获取订单状态
     *
     * @param orderId
     * @return
     */
    @AutoLog(value = "获取订单状态")
    @ApiOperation(value = "获取订单状态", notes = "params: orderId")
    @GetMapping(value = "/getOrderStatusInfo")
    public Result<?> getOrderStatusInfo(@RequestParam("orderId") String orderId) {
        Member member = verifyUserForApp();
        return Result.OK(iOrderBaseSDXService.getOrderStatusInfo(orderId));
    }

    /*@AutoLog(value = "添加购物车")
    @ApiOperation(value = "添加购物车", response = MemberCart.class)
    @PostMapping(value = "/addMemberCart")
    public Result<?> addMemberCart(@RequestBody MemberCart memberCart) {
        Member member = verifyUserForApp();
        if (!member.getId().equals(memberCart.getMemberId())) {
            return Result.error("参数错误~");
        }
        return shopCartService.add(memberCart);
    }

    @AutoLog(value = "我的购物车")
    @ApiOperation(value = "我的购物车", response = MemberCart.class)
    @PostMapping(value = "/memberCartList")
    public Result<?> memberCartList(@RequestBody MemberCart memberCart) {
        Member member = verifyUserForApp();
        if (!member.getId().equals(memberCart.getMemberId())) {
            return Result.error("参数错误~");
        }
        if (oConvertUtils.isEmpty(memberCart.getShopId())) {
            return Result.error("参数错误~");
        }
        List<MemberCart> memberCartList = shopCartService.list(new QueryWrapper<MemberCart>()
                .eq("member_id", memberCart.getMemberId())
                .eq("shop_id", memberCart.getShopId()));
        return Result.OK(memberCartList);
    }

    @AutoLog(value = "修改购物车")
    @ApiOperation(value = "修改购物车", response = MemberCart.class)
    @PostMapping(value = "/updMemberCart")
    public Result<?> updMemberCart(@RequestBody MemberCart memberCart) {
        Member member = verifyUserForApp();
        if (!member.getId().equals(memberCart.getMemberId()) || null == memberCart.getId() || memberCart.getId().isEmpty()) {
            return Result.error("操作失败~");
        }

        return Result.OK(shopCartService.updateById(memberCart));
    }

    @AutoLog(value = "删除购物车")
    @ApiOperation(value = "删除购物车", response = MemberCart.class)
    @GetMapping(value = "/delMemberCart")
    public Result<?> delMemberCart(@RequestParam("id") String id) {
        Member member = verifyUserForApp();
        MemberCart memberCart = shopCartService.getById(id);
        if (null == memberCart || !member.getId().equals(memberCart.getMemberId())
                || null == memberCart.getId() || memberCart.getId().isEmpty()) {
            return Result.error("操作失败~");
        }
        return Result.OK(shopCartService.updateById(memberCart));
    }*/


}
